import { request } from "../../request/index.js";
import { getSetting, chooseAddress, openSetting, showModal, showToast, requestPayment } from "../../utils/asyncWx.js";
/**
 * 1 页面被打开的时候 onShow
 *   0 onShow 不同于onLoad 无法在形参上接收 options参数
 *   0.5 判断缓存中有没有token
 *       1 没有 直接跳转到授权页面
 *       2 有 直接往下进行
 *   1 获取url上的参数type
 *   2 根据type来决定页面标题的数组元素 哪个被激活选中
 *   2 根据type 去发送请求获取订单数据
 *   3 渲染页面
 * 2 点击不同的标题 重新发送请求来获取和渲染数据
 */
Page({

    /**
     * 页面的初始数据
     */
    data: {
        tabs: [{
                id: 0,
                value: "全部",
                isActive: true
            },
            {
                id: 1,
                value: "待付款",
                isActive: false
            },
            {
                id: 2,
                value: "已完成",
                isActive: false
            }
        ],
        userInfo: {}
    },

    onShow() {
        // const token = wx.getStorageSync("token");
        // if (!token) {
        //     wx.navigateTo({
        //         url: '/pages/auth/index'
        //     });
        //     return;
        // }
        // 1 获取缓存中的用户信息
        const userInfo = wx.getStorageSync("userInfo");
        this.setData({
            userInfo
        });
        // 1 获取当前的小程序的页面栈-数组 长度最大为‘10’页面
        let pages = getCurrentPages();
        // 2 数组中 索引中最大的页面就是当前页面
        let currentPage = pages[pages.length - 1];
        // 3 获取url上的type参数
        let { type } = currentPage.options;
        if (!type) type = 1;
        // 4 激活选中页面标题 当type=1 index=0
        this.changeTitleByIndex(type - 1);
        this.getOrders(type);
    },

    // 获取订单列表的方法
    async getOrders(type) {
        const res = await request({ url: "/order/getAllordertable" });
        if (type === 2 || type === "2") {
            let orders = res.data.data.map(v => ({...v }));
            orders = orders.filter(v => v.state === 0);
            this.setData({
                // v=>({...v}) 对象展开原样返回
                orders: orders
            });
        } else if (type === 3 || type === "3") {
            let orders = res.data.data.map(v => ({...v }));
            orders = orders.filter(v => v.state === 1);
            this.setData({
                orders: orders
            });
        } else {
            let orders = res.data.data.map(v => ({...v }));
            this.setData({
                orders: orders
            });
        }
    },

    // 根据标题索引来选中 标题数组
    changeTitleByIndex(index) {
        // 2 修改源数组
        let { tabs } = this.data;
        tabs.forEach((v, i) => i === index ? v.isActive = true : v.isActive = false);
        // 3 赋值到data中
        this.setData({
            tabs
        })
    },

    handleTabsItemChange(e) {
        // 1 获取被点击的标题索引
        const { index } = e.detail;
        this.changeTitleByIndex(index);
        // 2 重新发送请求 type=1 index=0
        this.getOrders(index + 1);
    },

    // 查看订单详情
    async handleOrderDetail(e) {
        const { id } = e.currentTarget.dataset;
        const type = this.data.tabs.filter(v => v.isActive === true);
        wx.navigateTo({
            url: '/pages/order_detail/index?id=' + id + '&index=' + (type[0].id + 1),
            fail: () => {
                showToast({ title: "网络连接失败" });
            }
        });
    },

    // 删除订单
    async handleDeleteOrder(e) {
        try {
            const { orderid } = e.currentTarget.dataset;
            const type = this.data.tabs.filter(v => v.isActive === true);
            wx.showModal({
                title: '提示',
                content: '',
                showCancel: true,
                cancelText: '取消删除',
                cancelColor: '#000000',
                confirmText: '确认删除',
                confirmColor: '#3CC51F',
                success: (res) => {
                    if (res.confirm) {
                        const orderParams = {
                            ordertable_id: orderid,
                        };
                        request({ url: "/order/deleteByOrdertable_id", data: orderParams, method: "GET" });
                        setTimeout(() => {
                            this.getOrders(type[0].id + 1);
                        }, 1000);
                    } else if (res.cancel) {
                        showToast({ title: "取消删除", icon: "none" });
                    }
                }
            });

        } catch (error) {
            showToast({ title: "网络连接失败" });
        }
    },

    // 取消订单
    async handleCancelOrder(e) {
        try {
            const { orderid } = e.currentTarget.dataset;
            const type = this.data.tabs.filter(v => v.isActive === true);
            wx.showModal({
                title: '提示',
                content: '',
                showCancel: true,
                cancelText: '取消',
                cancelColor: '#000000',
                confirmText: '确认取消',
                confirmColor: '#3CC51F',
                success: (res) => {
                    if (res.confirm) {
                        const orderParams = {
                            ordertable_id: orderid,
                            state: 2
                        };
                        request({ url: "/order/modifyOrdertableState", data: orderParams, method: "GET" });
                        setTimeout(() => {
                            this.getOrders(type[0].id + 1);
                        }, 1000);
                    } else if (res.cancel) {
                        showToast({ title: "取消操作", icon: "none" });
                    }
                }
            });

        } catch (error) {
            showToast({ title: "网络连接失败" });
        }
    },

    // 点击支付
    async handleOrderPay(e) {
        const index = await request({ url: "/user/getByOpenId", data: { open_id: this.data.userInfo.open_id }, method: "GET" });
        if (index.data.data.length === 1 || index.data.data.length === "") {
            if (index.data.data[0].state === 1) {
                showToast({ title: "您已被封禁，详情请联系客服", icon: "none" });
                wx.removeStorageSync("userInfo");
                wx.removeStorageSync("cart");
                wx.removeStorageSync("address");
                wx.removeStorageSync("expiration");
                this.setData({
                    userInfo: []
                })
                setTimeout(function() {
                    wx.switchTab({
                        url: '/pages/user/index'
                    });
                }, 2000);
                return;
            }
            if (index.data.data[0].state === 2) {
                showToast({ title: "您已被封禁，详情请联系客服", icon: "none" });
                return;
            }
        }
        try {
            const { orderid } = e.currentTarget.dataset;
            const type = this.data.tabs.filter(v => v.isActive === true);
            wx.showModal({
                title: '支付',
                content: '',
                showCancel: true,
                cancelText: '取消支付',
                cancelColor: '#000000',
                confirmText: '确认支付',
                confirmColor: '#3CC51F',
                success: (res) => {
                    if (res.confirm) {
                        const orderParams = {
                            ordertable_id: orderid,
                            state: 1
                        };
                        request({ url: "/order/modifyOrdertableState", data: orderParams, method: "GET" });
                        setTimeout(() => {
                            this.getOrders(type[0].id + 1);
                        }, 200);
                    } else if (res.cancel) {
                        showToast({ title: "取消支付", icon: "none" });
                    }
                }
            });

        } catch (error) {
            showToast({ title: "网络连接失败" });
            console.error(error);
        }
    }

})